package com.zeny.xdclass.service.impl;

import com.zeny.xdclass.config.WeChatConfig;
import com.zeny.xdclass.domain.User;
import com.zeny.xdclass.mapper.UserMapper;
import com.zeny.xdclass.service.UserService;
import com.zeny.xdclass.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName UserServiceIMpl
 * @Description 用户服务
 * @Author zeny
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User saveWeChatUser(String code) {
        //获取access_token
        String accessTokenUrl = String.format(weChatConfig.getOpenAccessTokenRul(),
                weChatConfig.getWxopenAppid(), weChatConfig.getWxopenAppsecret(), code);
        Map<String, Object> map = HttpUtils.doGet(accessTokenUrl);
        if (map == null || map.isEmpty()) {
            return null;
        }
        String accessToken = (String) map.get("access_token");
        String openId = (String) map.get("openid");
        User dbUser = userMapper.findByopenid(openId);
        if (dbUser != null) {
            return dbUser;
        }
        //获取用户信息
        String userInfoUrl = String.format(weChatConfig.getOpenUserInfoUrl(), accessToken, openId);
        Map<String, Object> userMap = HttpUtils.doGet(userInfoUrl);
        if (userMap == null || userMap.isEmpty()) {
            return null;
        }
        String nickname = (String) userMap.get("nickname");
        Integer sex  = ((Double) userMap.get("sex")).intValue();
        String province = (String)userMap.get("province");
        String city = (String)userMap.get("city");
        String country = (String)userMap.get("country");
        String headimgurl = (String)userMap.get("headimgurl");
        try {
            nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
            province = new String(province.getBytes("ISO-8859-1"), "UTF-8");
            city = new String(city.getBytes("ISO-8859-1"), "UTF-8");
            country = new String(country.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException ignored) {

        }
        String addr = new StringBuilder(country).append("->").append(province).append("->").append(city).toString();
        //封装信息到user保存本地
        User user = new User();
        user.setName(nickname);
        user.setHeadImg(headimgurl);
        user.setCity(addr);
        user.setOpenid(openId);
        user.setSex(sex);
        user.setCreateTime(new Date());
        userMapper.save(user);
        return user;
    }
}
